const util = require('../../utils/util.js');
const api = require('../../config/api.js');
var WxParse = require('../../lib/wxParse/wxParse.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    hideBox: true, //立即预约
    start: 1,
    teacherId: -1, //老师id
    userId: -1, //用户id
    userData: [], //老师数据
    collectStatus: false, //收藏状态：false未收藏，true收藏
    comments: [], //用户评价信息
    isMask: false,  
    topicId: -1, //选择的约聊话题Id
    topicName:"", //选择的话题名称
    price:null, //选择的越聊价钱
    type:null, //选择约聊的方式
    searchCondition: {  //搜索评论分页
      pageSize: 3,
      pageNumber: 1,
      conditionList: [],
      sort: {},
    },
    pageNumber:2, //查看评论更多
    getCommentMore:true, //查看更多按钮
    selectTopicIndex:0, //选择约聊的顺序  默认第一条
    isDisabled:true, //按钮禁用
    selfShow: []
  },
  showHideBox: function() {
    this.setData({
      hideBox: !this.data.hideBox,
      isMask: !this.data.isMask
    })
  },
  close: function() {
    this.setData({
      hideBox: true,
      isMask: false,
      topicId: -1, //选择的约聊话题Id
      price: null, //选择的越聊价钱
      type: null, //选择约聊的方式
      topicName:"",
      selectTopicIndex:0,
      isDisabled:true
    })
  },
  // 查询导师详细信息
  getUserData() {
    var that = this;
    var teacherId = that.data.teacherId; //导师Id
    util.request(api.TutorInfo, {
      userId: this.data.userId,
      tutorId: teacherId
    }, 'POST').then(function(res) {
      if (res.code === 200) {
        //设置介绍文字
        let userEducationExperiencesTXT = "";
        for (let i in res.result.userEducationExperiences) {
          if (i == res.result.userEducationExperiences.length - 1) {
            userEducationExperiencesTXT += res.result.userEducationExperiences[i].college
          } else {
            userEducationExperiencesTXT += res.result.userEducationExperiences[i].college + " | "
          }
        }
        res.result.userEducationExperiencesTXT = userEducationExperiencesTXT.substring(0, userEducationExperiencesTXT.length)
        userEducationExperiencesTXT = "";

        //解析导师自我介绍富文本
        WxParse.wxParse('goodsDetail', 'html', res.result.descrition_NotFileter, that);
        let selfShowStr = res.result.selfShow
        if (selfShowStr){
          let selfShow = selfShowStr.split(",")
          that.setData({
            selfShow: selfShow
          })
        }
        //添加设置收藏
        that.setData({
          userData: res.result,
          collectStatus: res.result.isBeCollect == 0 ? false : true
        })
      }
    });
  },

  previewImage: function (e) {
    let images = []
    images.push(e.currentTarget.dataset.url)
    wx.previewImage({
      current: images, // 当前显示图片的http链接   
      urls: images // 需要预览的图片http链接列表   
    })

  },

  //查询所有评价信息
  getComment() {
    var that = this;
    var teacherId = this.data.teacherId;
    let userId = this.data.userId;

    let searchCondition = this.data.searchCondition;
    let condition = {
      operator: 1,
      code: 'tutorId',
      value: parseInt(teacherId),
      type: 'Number'
    }
    let condition1 = { operator: 1, code: 'userId1', value: parseInt(userId), type: "Number" }
    searchCondition.conditionList.push(condition)
    searchCondition.conditionList.push(condition1)

    util.request(api.GetCommet, searchCondition, 'POST', true).then(function(res) {
      if (res.code === 200) {
        that.setData({
          comments: res.result
        })
      }else{
        console.log(res.code)
        that.setData({
          getCommentMore: false
        })
      }
    });
  },
  //查看更多
  getCommentMore() {
    let that = this;
    let tutorId = this.data.teacherId;
    let userId = this.data.userId;

    let searchCondition = {
      conditionList: [
        { operator: 1, code: 'tutorId', value: parseInt(tutorId), type: "Number" },
        { operator: 1, code: 'userId', value:  parseInt(userId), type: "Number" }
      ],
      pageNumber: this.data.pageNumber,
      pageSize: 3,
      sort: {}
    }
    
    util.request(api.MoreGetCommet, searchCondition, 'POST', true).then(function (res) {
      if (res.code === 200) {
        //没有数据了 提示
        if(res.result.length == 0){
          wx.showToast({
            title: '没有更多数据',
            icon: 'none'
          });
          that.setData({
            getCommentMore:false
          })
        }else{
          //取出评论数据  合并更多与当前  设置下一页
          let temp_Arr = that.data.comments
          let new_Arr = temp_Arr.concat(res.result);
          let nextPage = ++that.data.pageNumber;
          that.setData({
            comments: new_Arr,
            getCommentMore:true,
            pageNumber: nextPage
          })
        }
       
      }else{
        wx.showToast({
          title: '没有更多数据',
          icon: 'none'
        });
        that.setData({
          getCommentMore: false
        })
      }
    });
    
  },
  //添加收藏
  addClollect() {
    var that = this;
    var teacherId = that.data.teacherId; //导师ID
    wx.getStorage({
      key: 'userInfo',
      success: function(res) {
        var userId = res.data.id //用户ID
        that.setData({
          userId: userId
        })
        let addCondition = {
          userId: userId,
          beUserId: parseInt(teacherId)
        }
        util.request(api.CollectAdd, addCondition, 'POST', false).then(function(res) {
          if (res.code === 200) {
            let collectStatus = null;
            if (res.result == 0) {
              collectStatus = false;
              wx.showToast({
                title: '取消成功',
                icon: ''
              })
            } else {
              collectStatus = true;
              wx.showToast({
                title: '收藏成功',
                icon: ''
              })
            }
            that.setData({
              collectStatus: collectStatus
            })
          }else{
            wx.showModal({
              title: '提示',
              content: '收藏错误',
              showCancel: false
            })
          }
        })
      },
    })
  },

  //选择越聊话题
  selectTopic: function(e) {
    this.setData({
      topicId: e.currentTarget.dataset.topicid,
      selectTopicIndex: e.currentTarget.dataset.index,
      topicName: e.currentTarget.dataset.topicname,
      price:null,
      type:null,
    })
  },
  //选择约聊方式 和价钱
  selectPrice:function(e){
    if (this.data.topicId <0){
      this.setData({
        isDisabled:true
      })
      wx.showModal({
        title: '提示',
        content: '请先选择话题',
        showCancel: false
      })
      return false
    }
    this.setData({
      price: e.currentTarget.dataset.price, //选择的越聊价钱
      type: e.currentTarget.dataset.type, //选择约聊的方式
      isDisabled:false
    })
  },
  //跳转流程页面
  toProcess:function(e){
    //用户不能给自己下单
    if (wx.getStorageSync('userInfo').id == this.data.teacherId){
      wx.showToast({
        title: '用户不能给自己下单',
        icon: 'none'
      });
      return false
    }
    //校验选择
    if(this.data.price == null || this.data.type ==null || this.data.topicId == -1 ||this.data.topicName ==""){
      wx.showModal({
        title: '提示',
        content: '话题/约聊方式未选择',
        showCancel: false
      })
      return false
    }
    //翻译约见参数
    let type = this.data.type == "voicePrice" ? 1:2
    wx.navigateTo({
      url: '../../myPages/process/process?topicId=' + this.data.topicId + '&price=' + this.data.price + '&type=' + type + '&topicName=' + this.data.topicName + '&toUserId=' + this.data.teacherId
    })
  },
  //点赞
  isUsed(e){
    let that = this;
    //发送参数
    let param = {
      userCommentId:e.currentTarget.dataset.id,
      userId: this.data.userId
    }
    //改变当前视图
    let parentId = e.currentTarget.dataset.parentid;
    let index = 0;
    for (let i = 0; i < this.data.comments.length;i++){
      if (this.data.comments[i].id == parentId){
        index = i;
      }
    }
    let deletedtodo = 'comments[' + index + '].userComments['+0+'].helpfulCount';
    util.request(api.IsUsed, param,'POST').then(function (res) {
      if(res.code == 200){
        wx.showToast({
          title: '点赞成功',
          icon: 'none'
        });
        let num = that.data.comments[index].userComments[0].helpfulCount
        that.setData({
          [deletedtodo]: ++num
        })
      }else{
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    if (options.scene) {
      //如果是导师生成的二维码扫进来了，携带了导师的id
      let scene = decodeURIComponent(options.scene);
      that.setData({
        teacherId: scene
      })
    }else{
      //接收小程序跳转时候传过来的参数
      this.setData({
        teacherId: options.teacherId
      });
    }
    var userId = wx.getStorageSync('userInfo').id //获取用户id
    if (userId == null || userId == undefined) {
      // wx.navigateTo({
      //   url: "../authorize/authorize"
      // })
    } else {
      that.setData({
        userId: userId
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function(e) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;
    if (this.data.teacherId != -1) {
      this.getUserData();
      this.getComment();
    } else {
      wx.showModal({
        title: '提示',
        content: '获取不到用户id',
        showCancel: false
      })
    }
    var userId = wx.getStorageSync('userInfo').id //获取用户id
    if (userId == null || userId == undefined) {
      wx.navigateTo({
        url: "../authorize/authorize"
      })
    } else {
      that.setData({
        userId: userId
      })
    }
  },
  // 添加提问
  goAsk:function(){
    wx.navigateTo({
      url: '../../myPages/Ask/Ask?teacherId=' + this.data.teacherId
    })
  },
  /** 
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function(e) {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let that = this;
    //拼接title
    let from = wx.getStorageSync('userInfo').nickName;
    let descrition = that.data.userData.tUser.fullName+"导师。简介" + that.data.userData.descrition + that.data.userData.tUser.fullName;
    let title = `${from}推荐了${descrition}`
    return {  
      title: title, // 转发后 所显示的title
      path: '/pages/index/index?teacherId=' + that.data.userData.tUser.id, // 相对的路径
      imageUrl:"/images/common/share_people.png",
      success: (res) => {    // 成功后要做的事情
        wx.getShareInfo({
          shareTicket: res.shareTickets[0],
          success: (res) => {
            
          },
          fail: function (res) { console.log(res) },
          complete: function (res) { console.log(res) }
        })
      },
      fail: function (res) {
      }
    }
  }
})